package com.wk.gray;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;

import java.util.List;
import java.util.Map;

/**
 * 客户端到服务的灰度发布规则
 */
public class GrayRule extends AbstractLoadBalancerRule {

	/**
	 * 根据用户信息选择服务
	 */
	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {

	}

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	private Server choose(ILoadBalancer lb, Object key) {
		Server server = null;
		while (server == null) {
			//从Eureka中获取所有可用服务
			List<Server> serverList = lb.getReachableServers();

			//获取当前线程的参数
			Map<String, String> map = RibbonParameters.get();
			String version = "";
			if (map != null && map.containsKey("version")) {
				version = map.get("version");
			}

			//根据用户选服务
			for (int i = 0; i < serverList.size(); i++) {
				//获取到用户请求参数中的version
				server = serverList.get(i);

				//获取在Eurkea中自定义的metadata数据
				Map<String, String> metadata = ((DiscoveryEnabledServer) server).getInstanceInfo().getMetadata();
				String version1 = metadata.get("version");

				//服务的metadata匹配用户的version
				if (version.trim().equals(version1)) {
					break;
				}
			}
		}
		return server;
	}
}
